package com.longxi.tianjintianbao.ui.presenter.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.model.Build;
import com.longxi.tianjintianbao.model.TabEntity;
import com.longxi.tianjintianbao.ui.activity.energy_read.EnergyReadListActivity;
import com.longxi.tianjintianbao.ui.activity.equipment.EquipmentActivity;
import com.longxi.tianjintianbao.ui.activity.oa.ReceiptListActivity;
import com.longxi.tianjintianbao.ui.activity.patrol.PatrolScanSearchActivity;
import com.longxi.tianjintianbao.ui.activity.repair.RepairListActivity;
import com.longxi.tianjintianbao.ui.activity.repair_publish.RepairActivity;
import com.longxi.tianjintianbao.ui.adapter.MainPagerAdapter;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.fragment.mian.HomeFragment;
import com.longxi.tianjintianbao.ui.fragment.mian.MeFragment;
import com.longxi.tianjintianbao.ui.fragment.mian.MessageFragment;
import com.longxi.tianjintianbao.ui.presenter.patrol.PatrolScanSearchAtPresenter;
import com.longxi.tianjintianbao.ui.view.main.IMainAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.widget.iosdialog.ActionSheetDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainAtPresenter extends BasePresenter<IMainAtView> {
    private String[] mTitles = {"消息", "工作", "联系人", "我的"};
    int[] mIconUnselectIds = {R.mipmap.ic_main_message_normal, R.mipmap.ic_main_home_normal, R.mipmap.ic_main_contact_normal, R.mipmap.ic_main_me_normal};
    int[] mIconSelectIds = {R.mipmap.ic_main_message_select, R.mipmap.ic_main_home_select, R.mipmap.ic_main_contact_select, R.mipmap.ic_main_me_select};

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private int nowPosition = 0;

    private MainPagerAdapter mainPagerAdapter;

    private int msgCount = 0;

    public static boolean isForeground = false;

    public MainAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initViewPager() {
        mainPagerAdapter = new MainPagerAdapter(mContext.getSupportFragmentManager());
        getView().getVp().setAdapter(mainPagerAdapter);
        getView().getVp().setOffscreenPageLimit(3);

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        tl_2();
        getView().getCtl().setCurrentTab(0);
    }

    /**
     * viewpager点击效果
     */
    private void tl_2() {
        getView().getCtl().setTabData(mTabEntities);
        getView().getCtl().setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                getView().getVp().setCurrentItem(position, false);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        getView().getVp().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                nowPosition = position;
                getView().getCtl().setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        getView().getVp().setCurrentItem(0);
    }

    /**
     * 弹出底部多选item
     */
    public void showSelectRepairArea() {
        new ActionSheetDialog(mContext)
                .builder()
                .setTitle("请选择报修区域")
                .addSheetItem("客户区域", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, RepairActivity.class);
                                mainIntent.putExtra(AppConst.REPAIRAREA,"indoorArea.json");
                                mainIntent.putExtra(AppConst.REGION,"0");
                                mContext.startActivity(mainIntent);
                            }
                        })
                .addSheetItem("公共区域", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, RepairActivity.class);
                                mainIntent.putExtra(AppConst.REPAIRAREA,"outdoorArea.json");
                                mainIntent.putExtra(AppConst.REGION,"1");
                                mContext.startActivity(mainIntent);
                            }
                        }).show();
    }

    /**
     * 弹出底部多选item
     */
    public void showSelectAss() {
        new ActionSheetDialog(mContext)
                .builder()
                .setTitle("请选择资产类别")
                .addSheetItem("设备", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, EquipmentActivity.class);
                                mainIntent.putExtra(AppConst.TYPE,"0");
                                mainIntent.putExtra(AppConst.TITLE,"设备");
                                mContext.startActivity(mainIntent);
                            }
                        })
                .addSheetItem("建筑物", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, EquipmentActivity.class);
                                mainIntent.putExtra(AppConst.TYPE,"1");
                                mainIntent.putExtra(AppConst.TITLE,"建筑物");
                                mContext.startActivity(mainIntent);
                            }
                        })
                .addSheetItem("房屋", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, EquipmentActivity.class);
                                mainIntent.putExtra(AppConst.TYPE,"2");
                                mainIntent.putExtra(AppConst.TITLE,"房屋");
                                mContext.startActivity(mainIntent);
                            }
                        }).show();
    }

    /**
     * 弹出底部多选item
     */
    public void showSelectBorrow() {
        new ActionSheetDialog(mContext)
                .builder()
                .setTitle("请选择单据类型")
                .addSheetItem("借款", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, ReceiptListActivity.class);
                                mainIntent.putExtra(AppConst.TYPE,"13");
                                mainIntent.putExtra(AppConst.TYPENAME,"借款");
                                mContext.startActivity(mainIntent);
                            }
                        })
                .addSheetItem("应付款项", ActionSheetDialog.SheetItemColor.Orange,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Intent mainIntent = new Intent(mContext, ReceiptListActivity.class);
                                mainIntent.putExtra(AppConst.TYPE,"280");
                                mainIntent.putExtra(AppConst.TYPENAME,"应付款项");
                                mContext.startActivity(mainIntent);
                            }
                        }).addSheetItem("转正", ActionSheetDialog.SheetItemColor.Orange,
                new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        Intent mainIntent = new Intent(mContext, ReceiptListActivity.class);
                        mainIntent.putExtra(AppConst.TYPE,"19");
                        mainIntent.putExtra(AppConst.TYPENAME,"转正");
                        mContext.startActivity(mainIntent);
                    }
                }).show();
    }

    OptionsPickerView pvCustomOptionsRepair;
    /**
     * 选择报修小区 如果只有一个小区直接跳转
     */
    public void showRepair() {
        String buildid = MyApplication.loginUser.buildid;
        String build = MyApplication.loginUser.build;
        List<String> buildidList= Arrays.asList(buildid.replace(" ", "").split(","));
        List<String> buildList= Arrays.asList(build.replace(" ", "").split(","));
        List<Build> localBuilds = new ArrayList<>();
        for (int i = 0; i < buildidList.size(); i++) {
            Build localBuild = new Build();
            localBuild.setBuildid(Integer.parseInt(buildidList.get(i)));
            localBuild.setBuild(buildList.get(i));
            localBuilds.add(localBuild);
        }
        if(buildidList.size() == 1){
            toRepairListActivity(buildidList.get(0), buildList.get(0));
            return;
        }
        if(pvCustomOptionsRepair != null){
            pvCustomOptionsRepair.show();
            return;
        }
        /**
         * @description
         *
         * 注意事项：
         * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
         * 具体可参考demo 里面的两个自定义layout布局。
         */
        pvCustomOptionsRepair = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                toRepairListActivity(localBuilds.get(options1).getBuildid() + "", localBuilds.get(options1).getBuild());
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvTitle = (TextView) v.findViewById(R.id.tv_title);
                        tvTitle.setText("请选择报事报修小区");
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptionsRepair.returnData();
                                pvCustomOptionsRepair.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptionsRepair.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .build();

        pvCustomOptionsRepair.setPicker(localBuilds);//添加数据
        pvCustomOptionsRepair.show();
    }

    public void toRepairListActivity(String buildid, String build){
        Intent mainIntent = new Intent(mContext, RepairListActivity.class);
        mainIntent.putExtra(AppConst.BUILDID,buildid);
        mainIntent.putExtra(AppConst.BUILD,build);
        mContext.startActivity(mainIntent);
    }

    OptionsPickerView pvCustomOptionsEnergyRead;
    /**
     * 选择报修小区 如果只有一个小区直接跳转
     */
    public void showtoEnergyRead() {
        String buildid = MyApplication.loginUser.buildid;
        String build = MyApplication.loginUser.build;
        List<String> buildidList= Arrays.asList(buildid.replace(" ", "").split(","));
        List<String> buildList= Arrays.asList(build.replace(" ", "").split(","));
        List<Build> localBuilds = new ArrayList<>();
        for (int i = 0; i < buildidList.size(); i++) {
            Build localBuild = new Build();
            localBuild.setBuildid(Integer.parseInt(buildidList.get(i)));
            localBuild.setBuild(buildList.get(i));
            localBuilds.add(localBuild);
        }
        if(buildidList.size() == 1){
            toEnergyReadListActivity(buildidList.get(0), buildList.get(0));
            return;
        }
        if(pvCustomOptionsEnergyRead != null){
            pvCustomOptionsEnergyRead.show();
            return;
        }
        /**
         * @description
         *
         * 注意事项：
         * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
         * 具体可参考demo 里面的两个自定义layout布局。
         */
        pvCustomOptionsEnergyRead = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                toEnergyReadListActivity(localBuilds.get(options1).getBuildid() + "", localBuilds.get(options1).getBuild());
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvTitle = (TextView) v.findViewById(R.id.tv_title);
                        tvTitle.setText("请选择能耗抄表小区");
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptionsEnergyRead.returnData();
                                pvCustomOptionsEnergyRead.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptionsEnergyRead.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .build();

        pvCustomOptionsEnergyRead.setPicker(localBuilds);//添加数据
        pvCustomOptionsEnergyRead.show();
    }

    public void toEnergyReadListActivity(String buildid, String build){
        Intent mainIntent = new Intent(mContext, EnergyReadListActivity.class);
        mainIntent.putExtra(AppConst.BUILDID,buildid);
        mainIntent.putExtra(AppConst.BUILD,build);
        mContext.startActivity(mainIntent);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mContext.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_SELECT_COMMUNITY:
                MeFragment meFragment = (MeFragment) mainPagerAdapter.getCurrentFragment();
                meFragment.meUi();
                break;
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
                if (data != null) {
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_SUCCESS) {
                            String result = bundle.getString(AppConst.RESULT_STRING);
                            try {
                                Log.d("二维码结果", result);
                                int a = Integer.parseInt(result);
                                Intent intent = new Intent(mContext, PatrolScanSearchActivity.class);
                                intent.putExtra(PatrolScanSearchAtPresenter.ADDRESSID, result);
                                mContext.startActivity(intent);
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                                MyUtils.showToast("该二维码不符合规则");
                            }
                        } else if (bundle.getInt(AppConst.RESULT_TYPE) == AppConst.RESULT_FAILED) {
                            MyUtils.showToast("解析二维码失败");
                        }
                    }
                }
                break;
        }
    }

    //刷新巡检消息角标
    public void refreshPatrolMessage() {
        HomeFragment homeFragment = (HomeFragment) mainPagerAdapter.getItem(1);
        homeFragment.refreshPatrolMessage();
    }

    //消息页面全部消息刷新
    public void refreshMessage(){
        MessageFragment messageFragment = (MessageFragment) mainPagerAdapter.getItem(0);
        messageFragment.refreshMessage(false);
//        nmb();
    }

    //工作页面全部消息刷新
    public void refreshHomeMessage(){
        HomeFragment homeFragment = (HomeFragment) mainPagerAdapter.getItem(1);
        homeFragment.refreshHomeMessage(false);
//        nmb();
    }

    //nmb刷新 用于到页面在刷新 因为服务器不支持多线程操作
    public void nmb() {
        if(!isForeground){
            return;
        }
        switch (nowPosition) {
            case 0:
                MessageFragment messageFragment = (MessageFragment) mainPagerAdapter.getItem(0);
                messageFragment.refreshMessage(true);
                break;
            case 1:
                HomeFragment homeFragment = (HomeFragment) mainPagerAdapter.getItem(1);
                homeFragment.refreshHomeMessage(true);
                break;
        }
    }

    /**
     * 给底部按钮增加消息角标
     * @param count
     */
    public void showMsg(int count) {
        getView().getCtl().showMsg(0, count);
    }
}
